package com.todod.common.http;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 响应数据
 *
 * @author gsh
 * @version 1.0
 * @date 2021/4/7 0007 14:13
 */
@Data
@Slf4j
public class ResponseData {

    private int statusCode; //响应码
    private String reasonPhrase; //reasonPhrase
    private String protocolVersion; //protocolVersion

    private Map<String, String> headers; // 响应头
    private String data; // 响应数据
    private Long time; // 响应时间

    public static ResponseData createRespone(CloseableHttpResponse response) {
        ResponseData responseData = new ResponseData();

        StatusLine statusLine = response.getStatusLine();
        responseData.setStatusCode(statusLine.getStatusCode());
        responseData.setProtocolVersion(statusLine.getProtocolVersion().toString());
        responseData.setReasonPhrase(statusLine.getReasonPhrase());

        Map<String, String> headers = new HashMap<>();
        responseData.setHeaders(headers);
        Header[] allHeaders = response.getAllHeaders();
        for (Header header : allHeaders) {
            headers.put(header.getName(), header.getValue());
        }
        try {
            Charset charset = StandardCharsets.UTF_8;
            try {
                String contentType = headers.get(HTTP.CONTENT_TYPE);
                if (StringUtils.isNotBlank(contentType)) {
                    String[] split = contentType.split("charset=");
                    if (split.length == 2) {
                        String c = split[1];
                        c = c.trim();
                        charset = Charset.forName(c);
                    }
                }
            } catch (Exception e) {
                log.warn("获取Charset错误:" + e.getMessage());
            }

            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String s = EntityUtils.toString(entity, charset);
                responseData.setData(s);
            }
        } catch (IOException e) {
            log.error("error", e);
            responseData.setData("获取响应数据失败");
        }

        return responseData;
    }
}
